﻿using System;
using System.Linq;
using System.Threading.Tasks;
using AyuBookmark.Common.Interfaces;
using AyuBookmark.Common.Models;
using AyuBookmark.Common.Extensions;
using Microsoft.Extensions.Logging;

namespace AyuBookmark.Service.Services
{
    /// <summary>
    /// 书签管理服务实现
    /// </summary>
    public class BookmarkManager : IBookmarkManager
    {
        private readonly IBookmarkRepository _bookmarkRepository;
        private readonly ICategoryRepository _categoryRepository;
        private readonly ILogger<BookmarkManager> _logger;
        private bool _isBrowserActive;
        private string _currentActiveUrl;

        /// <summary>
        /// 初始化书签管理器
        /// </summary>
        public BookmarkManager(
            IBookmarkRepository bookmarkRepository,
            ICategoryRepository categoryRepository,
            ILogger<BookmarkManager> logger)
        {
            _bookmarkRepository = bookmarkRepository ?? throw new ArgumentNullException(nameof(bookmarkRepository));
            _categoryRepository = categoryRepository ?? throw new ArgumentNullException(nameof(categoryRepository));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <inheritdoc />
        public void SetBrowserActiveState(bool isActive)
        {
            _isBrowserActive = isActive;
            if (!isActive)
            {
                _currentActiveUrl = null;
            }
        }

        /// <inheritdoc />
        public async Task HandleCurrentUrl(string url)
        {
            try
            {
                if (!_isBrowserActive || string.IsNullOrWhiteSpace(url) || url == _currentActiveUrl)
                {
                    return;
                }

                _currentActiveUrl = url;

                // 检查是否已存在该书签
                var existingBookmark = await _bookmarkRepository.GetByUrlAsync(url);
                if (existingBookmark == null)
                {
                    await CreateNewBookmark(url);
                }
                else
                {
                    await UpdateExistingBookmark(existingBookmark);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"处理URL失败: {url}");
            }
        }

        /// <inheritdoc />
        public async Task<BookmarkInfo> GetActiveBookmark()
        {
            if (string.IsNullOrEmpty(_currentActiveUrl))
            {
                return null;
            }

            var bookmark = await _bookmarkRepository.GetByUrlAsync(_currentActiveUrl);
            if (bookmark == null)
            {
                return null;
            }

            string categoryName = null;
            if (bookmark.CategoryId.HasValue)
            {
                var category = await _categoryRepository.GetByIdAsync(bookmark.CategoryId.Value);
                categoryName = category?.Name;
            }

            return new BookmarkInfo
            {
                Id = bookmark.Id,
                Url = bookmark.Url,
                Title = bookmark.Title,
                CategoryId = bookmark.CategoryId,
                CategoryName = categoryName
            };
        }

        /// <inheritdoc />
        public async Task UpdateBookmarkAccessTime(int bookmarkId)
        {
            try
            {
                var bookmark = await _bookmarkRepository.GetByIdAsync(bookmarkId);
                if (bookmark != null)
                {
                    bookmark.LastAccessed = DateTime.Now;
                    await _bookmarkRepository.UpdateAsync(bookmark);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新书签访问时间失败，ID: {bookmarkId}");
            }
        }

        #region 私有方法
        private async Task CreateNewBookmark(string url)
        {
            var newBookmark = new Bookmark
            {
                Url = url,
                Title = ExtractTitleFromUrl(url),
                CreatedTime = DateTime.Now,
                LastAccessed = DateTime.Now,
                // 设置默认分类
                CategoryId = await GetDefaultCategoryId()
            };

            await _bookmarkRepository.AddAsync(newBookmark);
            _logger.LogInformation($"已创建新书签: {url}");
        }

        private async Task UpdateExistingBookmark(Bookmark bookmark)
        {
            bookmark.LastAccessed = DateTime.Now;
            await _bookmarkRepository.UpdateAsync(bookmark);
            _logger.LogDebug($"已更新书签访问时间: {bookmark.Url}");
        }

        private async Task<int?> GetDefaultCategoryId()
        {
            try
            {
                var defaultCategory = (await _categoryRepository.FindAsync(c => c.Name == "未分类")).FirstOrDefault();
                return defaultCategory?.Id;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "获取默认分类ID失败");
                return null;
            }
        }

        private string ExtractTitleFromUrl(string url)
        {
            try
            {
                var uri = new Uri(url);
                return uri.Host.Replace("www.", "").Replace(".com", "");
            }
            catch (UriFormatException)
            {
                return url.Length > 50 ? url.Substring(0, 50) + "..." : url;
            }
        }
        #endregion
    }
}